//
//  SecondViewController.swift
//  QFImageMaskDemo
//
//  Created by Anakin chen on 2020/3/12.
//  Copyright © 2020 QF Network Technology. All rights reserved.
//

import UIKit

class SecondViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
    
    var imagePicker: UIImagePickerController?

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    private func open() {
        if UIImagePickerController.isSourceTypeAvailable(.savedPhotosAlbum) {
            let imagePicker = UIImagePickerController()
            imagePicker.sourceType = .savedPhotosAlbum
            imagePicker.delegate = self
            imagePicker.allowsEditing = false
            self.imagePicker = imagePicker
            self.present(imagePicker, animated: true, completion: nil)
        }
        else {
            print("读取相册失败")
        }
    }
    
    private func open2() -> UIImage? {
        let manager = FileManager.default
        let url = manager.urls(for: .documentDirectory, in: .userDomainMask).first! as NSURL
        let filePath = url.appendingPathComponent("QFShotScreenImage")!.path
        if let value = NSKeyedUnarchiver.unarchiveObject(withFile: filePath) as? Data {
            let image = UIImage(data: value)
            return image
        }
        return nil
    }

    // Mark: UIImagePickerControllerDelegate
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        imagePicker!.dismiss(animated: true, completion: nil)
        
        if let image = info[.originalImage] as? UIImage {
            let infoStr = QFLSBMan.decode(image: image)
            if let vc = UIApplication.shared.keyWindow?.rootViewController {
                let alert = UIAlertController(title: "解密结果", message: infoStr ?? "解密失败", preferredStyle: .alert)
                let cancel = UIAlertAction(title: "确定", style: .cancel) { (UIAlertAction) in
                }
                alert.addAction(cancel)
                vc.present(alert, animated: true, completion: nil)
            }
        }
    }
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        imagePicker!.dismiss(animated: true, completion: nil)
    }
    
    @IBAction func showLSBInfoAction(_ sender: Any) {
        open()
    }
    
}

